$(() => {

    //刷新验证码
    $("#captcha-img").click(function () {
        $(this).attr("src", ctx + "/admin/captcha?t=" + Math.random());
    });

    //登录
    $("#login-btn").click(function () {
        let username = $("#username").val();
        let password = $("#password").val();
        let captcha = $("#captcha").val();

        //校验
        if (!username) {
            layer.msg("用户名不可为空");
            return;
        }

        if (!password) {
            layer.msg("密码不可为空");
            return;
        }

        if (!captcha) {
            layer.msg("验证码不可为空");
            return;
        }


        $.ajax({
            url: ctx + "/admin/login",
            method: "post",
            data: {
                username,
                password,
                captcha
            },
            success(resp) {
                $("#captcha-img").trigger("click");//刷新验证码

                if (resp.success) {
                    location.href = ctx + "/admin/main";//跳转到后台首页
                } else {
                    layer.msg(resp.error || "认证失败，请检查后重试");
                }
            }
        });
    });
});